<?php
namespace Admin\Controller;
use Think\Controller;
/*
 ×商品管理控制器
 ×
 */
class ItemController extends AdminController {
	public function index(){
		$page=I('get.page','1','strip_tags');
        $count=M('item')->where('isdel=0')->count();
        $pagearr= getPageArr($page,C('PAGESIZE'),$count);
		$result=M('item')->where('isdel=0')
		                 ->limit($pagearr['start'],$pagearr['pagesize'])
		                 ->order('itemid desc')->select();
		$this->assign('items',$result);
		$this->assign('pagearr',$pagearr);
		$this->display('index');
	}
	/*
	 *添加商品
	 */
	public function addItem(){
		$typeid=I('get.typeid','','strip_tags');
		//获取所有类目
		$type=new \Admin\Controller\TypeController();
		$typearr=$type->getListCat();
		
		//如果typeid非空需要选择商品属性
		if(!empty($typeid)){
		//类目关联的品牌
		 $brands=M('type_brand a ')->join('inner join '.C('DB_PREFIX').'brand b on a.brandid= b.brandid')
		         ->where('b.isdel=0 AND a.typeid='.$typeid)
		         ->getField('b.brandid,b.brandname');
		//获取该类目下的所有属性
		$typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
		          ->where('a.typeid=%d',$typeid)
		          ->getField('b.propertyid,a.typeid,a.typename,b.propertyname');
		  if(!empty($typeproperty))
		  {
		  	foreach($typeproperty as $key=>&$value)
		  	{
		 	$where['propertyid']=$key;
		 	$value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
		 		             ->where('a.propertyid=%d',$where['propertyid'])
		 		             ->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
		 	}

		  }
		 
		 //获取当前类目下的规格
		 $spec_type=M('type_spec a ')->join('inner join '.C('DB_PREFIX').'spec b  on a.specid =b.specid ')
		  			->where('a.typeid=%d',$typeid)->getField('a.specid,a.typeid,b.`name`');
		 if(!empty($spec_type)){
		 	foreach($spec_type as $key=>&$value){
		 			$where['specid']=$key;
		 			$value['specval']=M('specval')->where('specid=%d',$where['specid'])->getField('specvalid,specid,name');
		 	}
		 }
		 $map['state']=array('in','0,1');
		 $activity=M('activity')->where($map)->Field("id,theme")->select();
			$this->assign('activity',$activity);
		 $this->assign('typearr',$typearr);//分类树
		 $this->assign('specs',$spec_type);
		 $this->assign('brands',$brands);
		 $this->assign('typeproperty',$typeproperty);
		 $this->assign('typeid',$typeid);
		 $this->display('pro_spec');

		}else{
			
			$this->assign('typearr',$typearr);//分类树
			$this->display();
		}
		
	}
	//保存商品
	public function saveItem(){
	//获取商品基本 信息
	$data['status']=I('post.status','','strip_tags');
	$data['itemname']=I('post.itemname','','strip_tags');
	$data['bn']=I('post.bn','','strip_tags');
	$data['price']=I('post.price',0,'strip_tags');
	$data['mkprice']=I('post.mkprice',0,'strip_tags');
	$data['inventory']=I('post.inventory',0,'strip_tags');
	$data['typeid']=I('post.itemtype','','strip_tags');
	$data['brandid']=I('post.brand','','strip_tags');
	$data['createtime']=time();
	$data['activityid']=$_POST['activityid'];
	$data['discount']=$_POST['discount'];

	$itemdescdata=!empty($_POST['editorValue'])?$_POST['editorValue']:'';
	//获取商品属性数组
	$property=I('post.proper','','strip_tags');
	//商品规格
	$spec=I('post.spec','','strip_tags');
	//货品规格
	$prospec=I('post.prospec','','strip_tags');
	//货品库存
	$pinventory=I('post.pinventory','','strip_tags');
	$pprice=I('post.pprice','','strip_tags');
    //调用上传图片
    if(!empty($_FILES['listimg']['tmp_name'])){
	 	$data['itemimg']=$this->uploadimg();

	     if ($data['itemimg']==false)
	     {
	     	$this->error('图片尺寸不符');
	     	//echo  "<script type='text/javascript'>alert('图片尺寸不符');window.history.go(-1);</script>";die;
	     }
	 }

	$item=M('item');
	$itemid=$item->data($data)->add();
	if (!empty($itemid)) {
		$itemdesc=M('item_desc');
		$itemdesc->create();
		$itemdesc->itemid=$itemid;
		$itemdesc->itemdesc=$itemdescdata;
		$itemdesc->add();
	}
	//保存产品属性
	if(!empty($itemid)){
        
        if(!empty($property))
        {
        $item_property=M('item_property');
		$datalist=array();
		foreach($property as $key=>$value)
		{
			$datalist[]=array('itemid'=>$itemid,'propertyid'=>$key,'propertyvalueid'=>$value);
		}
		//批量保存商品属性
		$item_property->addAll($datalist);
		}	
        //保存商品规格
        if(!empty($spec)){
        	$item_spec=M('item_spec');
        	$datalist=array();
        	foreach($spec as $key=>$value)
        	{
        		$datalist[]=array('itemid'=>$itemid,'specid'=>$key,'self'=>serialize($value));
        	}
        	//批量保存到cart_item_spec 表中
        	$item_spec->addAll($datalist);
        }

        //如果商品有规格和价格和库存，则此商品为货品,需向product 表中保存一份,商品必须填写规格，价格和库存
        if(!empty($prospec)){

        	$product=M('product');
        	$product_spec=M('product_spec');
 			$spids=array_keys($prospec);
        	$prodata=array();
        	foreach($pprice as $key=>$value)
        	{
        		//$datalist=array('itemid'=>$itemid,'price'=>$value,'inventory'=>$inventory[$key]);
        		
        		//保存货品规格值
        		$prodata=array('inventory'=>$pinventory[$key],'price'=>$pprice[$key],'itemid'=>$itemid);
        		$productid=$product->add($prodata);

        		foreach($spids as $k=>$specid)
        		{
        			$specdata[]=array('productid'=>$productid, 'specid'=>$specid,
        				"specvalid"=>$prospec[$specid][$key], "itemid"=>$itemid, "typeid"=>$data['typeid']);

        		}

        	}
        	
        	
        	$result=$product_spec->addAll($specdata);

        	if(!$result)
        	{
        		echo "<script type='text/javascript'>alert('添加商品失败'); window.history.go(-1);</script>";
        	}

        }
          
	}

	if($itemid || $result){
		//echo "<script type='text/javascript'>alert('添加商品成功');</script>";
		$this->success('添加产品成功');
	}
	
	}

	/*
	 *编辑产品
	 *@param  itemid 
	 */
	public function editItem(){
      $itemid=I('get.itemid','','strip_tags');
      if(!$itemid) return false;
      //获取分类树
      $type=new \Admin\Controller\TypeController();
	  $typearr=$type->getListCat();
      //获取商品基本信息
      $item=M('item');
      $iteminfo=$item->where('itemid=%d',$itemid)->select();
      //获取该类目下的所有属性
		$typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
		          ->where('a.typeid=%d',$iteminfo[0]['typeid'])
		          ->getField('b.propertyid,a.typeid,a.typename,b.propertyname');
		  if(!empty($typeproperty))
		  {
		  	foreach($typeproperty as $key=>&$value)
		  	{
		 	$where['propertyid']=$key;
		 	$value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
		 		             ->where('a.propertyid=%d',$where['propertyid'])
		 		             ->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
		 	}

		  }  
		//获取已选择的属性
		$seledpro=M('item_property')->where('itemid=%d',$iteminfo[0]['itemid'])->getField('propertyid,propertyvalueid');
		 foreach($typeproperty as $key=>&$value)
		 {
             
		 	foreach($value['select'] as $k=>&$v)
		 	{
		 		
		 		if($v['valueid']==$seledpro[$key])
		 		{

		 			$v['selected']='true';
		 		}
		 	}
		 }
		//获取该类目下所有品牌
		 $brands=M('type_brand a ')->join('inner join '.C('DB_PREFIX').'brand b on a.brandid= b.brandid')
		         ->where('b.isdel=0 AND a.typeid='.$iteminfo[0]['typeid'])
		         ->getField('b.brandid,b.brandname');
		 
		 //获取该类目下所有规格
		 $spec_type=M('type_spec a ')->join('inner join '.C('DB_PREFIX').'spec b  on a.specid =b.specid ')
		  			->where('a.typeid=%d',$iteminfo[0]['typeid'])->getField('a.specid,a.typeid,b.`name`');
		
		 if(!empty($spec_type))
		 {
		 	foreach($spec_type as $key=>&$value)
		 	{
		 			$where['specid']=$key;
		 			$value['specval']=M('specval')->where('specid=%d',$where['specid'])->getField('specvalid,specid,name');
		 	}
		 }
		 //该产品选中的规格
		 $serspec=M('item_spec')->where('itemid=%d',$itemid)->getField('specid,self');

		
		 foreach($serspec as &$v){
		 	$v=unserialize($v);

		 }
		
		 foreach($spec_type as $key=>&$value){
		 	foreach($value['specval'] as $k=>&$v){
		 		foreach($serspec[$key] as $i=>$sname)
		 		 {
		 		 	if($i==$v['specvalid']){
		 		 		$v['checked']='true';
		 		 	}
		 		}
		 		
		 	}
		 }
		
		//判断此商品是否为货品(即不同规格对应不同价格和库存)
	  $products=M('product')->where('itemid=%d',$itemid)->getField('productid,itemid,inventory,price');
	  if($products){
         $productspecs=M('product_spec')->where('itemid=%d',$itemid)->select(); 
         foreach($productspecs  as $spec){
         		$products[$spec["productid"]]["specs"][$spec["specid"]] =$spec["specvalid"];
         }  
	  }
	  //获取商品详情
	  $detail=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');

/////获取折扣
	  $discount=M('item')->where('itemid=%d',$itemid)->getField('discount');
	  $this->assign('discount',$discount);


	 ///获取商品参与的活动
	  $map['id']=M('item')->where('itemid=%d',$itemid)->getField("activityid");
	  $theme=M('activity')->where($map)->getField("theme");
	  $this->assign('theme',$theme);
	 ////获取所有的活动列表
		 $activity=M('activity')->Field("id,theme")->select();
			$this->assign('activity',$activity);
	  $this->assign('detail',$detail);
	  $this->assign('typearr',$typearr);
	  $this->assign('products',$products);
 	  $this->assign('iteminfo',$iteminfo[0]);
	  $this->assign('brands',$brands);
	  $this->assign('typeproperty',$typeproperty);
	  $this->assign('specs',$spec_type);
	  
      $this->display('edititem');
	}


	//更新产品
	public function updateItem(){
$data['activityid']=$_POST['activityid'];
$data['discount']=$_POST['discount'];
	 $data['modifietime']=time();
	 $itemid=I('post.itemid','','strip_tags');
	 $data['typeid']=I('post.typeid','','strip_tags');
	 $data['itemname']=I('post.itemname','','strip_tags');
	 $data['bn']=I('post.bn','','strip_tags');
	 $data['brand']=I('post.brand','','strip_tags');
	 $data['price']=I('post.price','','strip_tags');
	 $data['mkprice']=I('post.mkprice','','strip_tags');
	 $data['inventory']=I('post.inventory','','strip_tags');
	 $data['status']=I('post.status','','strip_tags');
	 //商品详情
	 $detail['itemdesc']=$_POST['editorValue'];
	 $typeid=I('post.itemtype','','strip_tags');
	 $proper=I('post.proper','','strip_tags');
	 $spec=I('post.spec','','strip_tags');
	 
	 //调用上传图片
	 
	 if(!empty($_FILES['listimg']['tmp_name'])){
	 	$data['itemimg']=$this->uploadimg();

	    if ($data['itemimg']==false)
	     {
	     	$this->error('图片尺寸不符');
	     	//echo  "<script type='text/javascript'>alert('图片尺寸不符');window.history.go(-1);</script>";die;
	     }
	 }
     
	 if($itemid){
	 	//更新基本信息
	 	$item=M('item');
	 	$result=$item->where('itemid=%d',$itemid)->save($data);

        //更新商品详情
        $ret=M('item_desc')->where('itemid=%d',$itemid)->getField('itemid');
        if(!$ret){
        	$detail['itemid']=$itemid;
        	M('item_desc')->add($detail);
        }else{

        	M('item_desc')->where('itemid=%d',$itemid)->save($detail);
        }
	 	//更新属性
	 	$item_property=M('item_property');
	 	
	 	foreach($proper as $key=>$value){
	 		$map['propertyvalueid']=$value;
	 		$tempres=$item_property->where('itemid=%d and propertyid=%d',$itemid,$key)->count();
	 		if(!empty($tempres)){
	 			$result=$item_property->where('itemid=%d and propertyid=%d',$itemid,$key)->save($map);
	 		}else{
	 			$map['itemid']=$itemid;
	 			$map['propertyid']=$key;
	 			$result=$item_property->add($map);
	 		}
	 		
	 	}

        
	 	//更新商品规格
	 	//var_dump($specs);die;
	 	$item_spec=M('item_spec');
	 	$map='';
	 	foreach($spec as $key=>$value){
	 		$map['self']=serialize($value);
	 		$result=$item_spec->where('itemid=%d and specid=%d',$itemid,$key)->save($map);
	 	}
	 	
	 	//更新货品规格
	 	$prospec=I('post.prospec','','strip_tags');

	 	$pprice=I('post.pprice','','strip_tags');
	 	$pinventory=I('post.pinventory','','strip_tags');
	 	$replacedata=array();
	 	$specids = array_keys($prospec);
	 	$data=array();
	 	foreach($pprice as $k => $v) 
						{
							$data = array("inventory"=>$pinventory[$k],"price"=>$pprice[$k],"itemid"=>$itemid);
							if($this->cstrpos($k,"key_")) 
							{ //如果是更新
								$productid = trim($k,"key_");
								//unset($products[$productid]);
								//DB::getDB()->update("product",$data,"productid='$productid'");
								M('product')->where('productid=%d',$productid)->save($data);

								foreach($specids as $specid) 
								{
									$replacedata = array("productid"=>$productid, "specid"=>$specid, "specvalid"=>$prospec[$specid][$k],
														   "itemid"=>$itemid,
														   "typeid"=>$typeid);
		$result=M('product_spec')->where('productid=%d and specid=%d',$productid,$specid)->save($replacedata);
								
								}
						//
							}else 
							{ //增加
					
								//$productid = DB::getDB()->insert("product",$data);
								/*foreach($specids as $specid) 
								{
									$replacedata[] = array("productid"=>$productid,
														   "specid"=>$specid,
														   "specvalid"=>$specs[$specid][$k],
														   "itemid"=>$itemid,
														   "typeid"=>$typeid);
								}*/
							}
	                    }
	                    
						//if($replacedata) DB::getDB()->replaceMulti("product_spec",$replacedata);
	 }

	 //更新成功
	  $this->success('修改成功','index');

	 
	}

	//公共方法
	public function cstrpos($haystack,$needle) {
	
	return strpos(strval($haystack),strval($needle)) !== false;
}
//上传图片
	public function uploadimg(){
			//保存商品图片
		$config['path']=C('Admin_IMG_PATH');
		$config['maxwidth']=C('LIST_MAX_WIDTH');
		$config['maxheight']=C('LIST_MAX_HEIGHT');
		 //判断是那个供应商上传的，重新定义图片路径
		 if(!file_exists($config['path']))
		 {	
		 	mkdir( $config['path'], 0777 , true );

		 }
		 $config['maxsize']=C('IMG_MAX_SIZE');
		 $img=imgUpload($config);
		 //上传出错
		 if(is_string($img)){
		 	return false;
		 }
		 $imginfo=$img['listimg'];
		 if(!empty($imginfo['savename']))
		 {
				$itemimg=substr(C('Admin_IMG_PATH'),1).$imginfo['savepath'].$imginfo['savename'];

		 }

		 return $itemimg;
	}


}